<template>
  <div>
    <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
      <el-form :model="queryParams.param" ref="draftSearchForm" :inline="true" v-show="showSearch" label-width="auto"
        label-position="left" :rules="shopProductRules">
        <el-form-item label="来源网站" prop="collectionSiteId">
          <el-select v-model="queryParams.param.collectionSiteId" placeholder="请选择" clearable filterable reserve-keyword
            style="width: 200px" @change="choseWebSite">
            <el-option v-for="dict in host_type" :key="dict.di" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ID" prop="newIDs">
          <el-input type="number" v-model.trim="queryParams.param.newIDs" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="采集商品分类" prop="rawCategoryId">
          <el-select v-model="queryParams.param.rawCategoryId" placeholder="请选择" clearable filterable reserve-keyword
            style="width: 200px">
            <el-option v-for="dict in site_currency_raw" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="来源语言" prop="languageId">
          <el-select v-model="queryParams.param.languageId" placeholder="请选择" clearable filterable reserve-keyword
            style="width: 200px">
            <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="币种" prop="currencyId">
          <el-select v-model="queryParams.param.currencyId" placeholder="请选择" clearable filterable reserve-keyword
            style="width: 200px">
            <el-option v-for="dict in sys_currency_code" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名" prop="name">
          <el-input v-model.trim="queryParams.param.name" placeholder="请输入" clearable />
        </el-form-item>
      </el-form>
    </searchBox>
    <div class="tabs_box">
      <el-tabs v-model="queryParams.param.auditStatus" class="mb8 demo-tabs" type="card" @tab-change="changeAuditStatus"
        style="width: 100%">
        <el-tab-pane v-for="dict in audit_type" :key="dict.value" :label="dict.label" :name="dict.value" />
      </el-tabs>
      <div style="position: absolute; right: 0; top: 5px">
        <el-button v-if="showBtn" class="mb8" type="primary" @click="handleCheck">快速审核</el-button>
        <el-button v-if="showBtn" class="mb8" type="primary" @click="handleConditions">批量审核
        </el-button>
        <el-button class="mb8" type="danger" @click="handleDone(ids)">批量删除
        </el-button>
      </div>
    </div>
    <el-table :data="draftList" @selection-change="handleSelectionChange" style="height: calc(100vh - 340px)"
      v-loading="loading">
      <el-table-column type="selection" :selectable="rowSelectable" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="100" />
      <el-table-column label="商品图" align="center" width="80">
        <template #default="scope">
          <image-preview :src="scope.row?.mainImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品名" align="left" prop="name" width="500">
        <template #default="scope">
          <el-link :href="scope.row.originUrl" target="_blank" :underline="false">{{
            scope.row.name
          }}</el-link>
          <div class="product_tag">
            <el-tag v-for="(category, index) in scope.row?.rawCategories" :key="index" type="primary">
              {{ category.name }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="采集价格" width="200">
        <template #default="scope">
          <el-tooltip placement="top">
            <template #content>
              <div>
                {{ scope.row.currencyName }}：{{
                  scope.row.price }} {{ scope.row.symbol
                }}
                <br />
                人民币：{{ scope.row.cnyprice }} ￥
              </div>
            </template>


            <div>
              {{ scope.row.price }} {{ scope.row.symbol
              }}
              <br />
              <el-text type="info"> {{ scope.row.cnyprice }} ￥</el-text>
            </div>

          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="来源网站">
        <template #default="scope">
          <div class="container">
            <el-button type="primary" size="small"> {{ scope.row?.languageName }}</el-button>
            <el-link :href="scope.row.originUrl" target="_blank" :underline="false">{{
              scope.row.collectionSiteName
            }}</el-link>
            <el-text>{{ scope.row.collectionTypeName }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="采集时间" prop="newCreated" align="center" width="200" />
      <el-table-column label="状态" width="150" align="center">
        <template #default="scope">
          <el-text :type="scope.row.newType.elTagClass">{{ scope.row.newType.label }}</el-text>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" prop="auditRemark">
        <template #default="scope">
          <el-tooltip effect="dark" placement="top-start">
            <template #content>
              <div style="max-width: 500px;">
                {{ scope.row.auditRemark }}
              </div>
            </template>
            <el-text line-clamp="2">
              {{ scope.row.auditRemark }}
            </el-text>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-button type="primary" link @click="handleAudit(1, scope.row)"
              v-if="scope.row?.auditStatus != 'passed'">审核</el-button>
            <el-dropdown @command="(command) => handleMining(scope.row, command)"
              v-if="scope.row?.auditStatus != 'passed'">
              <el-button type="primary" link>重采
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="item in incidentList" :key="item.id" :command="item">
                    <el-text :type="item.type">{{ item.title }}</el-text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" link @click="handleAudit(0, scope.row)"
              v-if="scope.row?.auditStatus == 'passed'">详情</el-button>
            <el-button v-if="scope.row?.auditStatus != 'passed'" link type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="批量审核" v-model="openCollect" width="500px" append-to-body @close="collectCancel">
      <el-form ref="collectFormRef" :model="queryParams.param" :rules="rules">
        <el-form-item label="来源网站" prop="collectionSiteId" required>
          <el-select v-model="queryParams.param.collectionSiteId" placeholder="请选择" @change="choseWebSite">
            <el-option v-for="dict in host_type" :key="dict.di" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="rawCategoryId">
          <el-select v-model="queryParams.param.rawCategoryId" placeholder="请选择" clearable filterable reserve-keyword
            style="width: calc(100% - 10px); margin-left: 10px">
            <el-option v-for="dict in site_currency_raw" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus" required>
          <el-select v-model="queryParams.param.auditStatus" placeholder="请选择" clearable style="width: 100%" disabled>
            <el-option v-for="dict in audit_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="collectSubmitForm('passed')" :loading="batchLoadIng">通 过</el-button>
        <el-button type="danger" @click="collectSubmitForm('notPassed')" :loading="batchLoadIng">不通过</el-button>
      </template>
    </el-dialog>

    <BatchReview :ids="ids" :speedVisible="speedVisible" @speedCancel="speedCancel" @handleSpeedSure="handleSpeedSure">
    </BatchReview>

    <!-- 审核产品草稿对话框 -->
    <Examine :auditOpen="auditOpen" :publicItem="auditForm" :showDetails="showDetails" @auditCancel="auditCancel"
      @auditsubmitForm="auditsubmitForm"></Examine>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import Examine from "./components/examine.vue";
import BatchReview from "./components/batchReview.vue";
import { ArrowDown } from "@element-plus/icons-vue";
const loading = ref(true)
const activeName = ref("first");
const { proxy } = getCurrentInstance();
const showBtn = ref(true);
const sys_language_type = ref([]); //获取语言类别
const sys_currency_code = ref([]); //获取货币类别
const sys_currency_raw = ref([]); //获取采集分类商品数据
const site_currency_raw = ref([]); //批量审核==》来源网站==>获取采集分类商品数据

const host_type = ref([]); //获取来源网站
const { audit_type } = proxy.useDict("audit_type");
const ids = ref([]);
const showSearch = ref(true);
const total = ref(1);
const draftList = ref([]);
const auditOpen = ref(false); //默认审核页面关闭
const openCollect = ref(false);
const showDetails = ref(false);
const speedVisible = ref(false);
const batchLoadIng = ref(false)//默认批量按钮是关闭的

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  param: {
    collectionSiteId: null, //来源网站id
    languageId: null, //来源语言id
    currencyId: null, //来源货币id
    name: "", //商品名
    rawCategoryId: "", //采集商品分类
    auditStatus: "notAudited",
    newIDs: '',
    ids: [],
  },
});

const auditForm = ref({});
onMounted(() => {
  getLanguage();
  getList();

});

/** 查询产品草稿列表 */
const getList = () => {
  product.draft
    .productdraftList({
      data: queryParams,
    })
    .then((response) => {
      total.value = response.total;
      if (response.code === 200) {
        loading.value = false
        response.data = response.data.map((code) => {
          return {
            ...code,
            newType: audit_type.value.find(e => e.value === code.auditStatus),
            newCreated: proxy.DateTime(code.created),
            rowStatue: code.auditStatus === "passed" ? 1 : 0,
          };
        });
      }
      draftList.value = response.data;
    });
};
// 审核取消按钮
const auditCancel = () => {
  auditOpen.value = false;
};

// 商品采集取消按钮
const collectCancel = () => {
  proxy.resetForm("collectFormRef");
  openCollect.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  proxy.$refs["draftSearchForm"].validate((valid) => {
    if (!valid) return
    if (queryParams.param.newIDs) {
      queryParams.param.ids = []
      queryParams.param.ids.push(queryParams.param.newIDs)
      queryParams.param.ids = queryParams.param.ids.map(Number)
    }
    getList();
  })
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.param.ids = []
  proxy.resetForm("draftSearchForm");
  getList();
};
// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
};
// 筛选条件批量审核
const handleConditions = () => {
  site_currency_raw.value = []
  openCollect.value = true;
  queryParams.param.auditStatus = "notAudited";
  getList();
};
// 勾选ID批量审核
const handleCheck = () => {
  if (!ids.value.length) return proxy.$modal.msgWarning(`请勾选ID`);
  speedVisible.value = true;
  // proxy.$modal
  //   .confirm(`是否确认审核已选择的${ids.value.length}个商品`)
  //   .then(() => {
  //     publicFastId(1, ids.value);
  //   });
};

// 列表审核按钮弹出操作
const handleAudit = (index, row) => {
  if (index) {
    showDetails.value = true;
    auditOpen.value = true;
    auditForm.value = row;
  } else {
    showDetails.value = false;
    auditOpen.value = true;
    auditForm.value = row;
  }
};

// 商品采集提交按钮
const collectSubmitForm = (status) => {
  proxy.$refs["collectFormRef"].validate((valid) => {
    if (!valid) return;
    batchLoadIng.value = true
    product.draft
      .productdraftAuditbatch({
        data: {
          collectionSiteId: queryParams.param.collectionSiteId,
          auditStatus: queryParams.param.auditStatus,
          rawCategoryId: queryParams.param.rawCategoryId,
          status: status,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          batchLoadIng.value = false
          openCollect.value = false;
          proxy.resetForm("collectFormRef");
          resetQuery();
        }
      }).catch(err => {
        proxy.$modal.msgWarning('发生错误，请联系后端人员');
        batchLoadIng.value = false

      })
  });
};
// 审核提交按钮
const auditsubmitForm = (e) => {
  let newArrayId = [];
  newArrayId.push(auditForm.value.id);
  publicFastId(0, newArrayId, e);
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  var newArray = [];
  newArray.push(row.id);
  handleDone(newArray)
};
const handleDone = (newArray) => {
  if (!newArray.length) return proxy.$modal.msgWarning(`请勾选ID`);

  proxy.$modal
    .confirm("是否确认删除此数据项？")
    .then(() => {
      product.draft
        .productdraftDeletebatch({
          data: {
            ids: newArray,
          },
        })
        .then((res) => {
          proxy.$modal.msgSuccess("删除成功");
          getList();
        });
    })

};


// 获取语言
const getLanguage = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {},
  };
  product.language.languageList().then((res) => {
    sys_language_type.value = res.data;
  });
  // 获取货币
  product.currency.currencyList().then((res) => {
    sys_currency_code.value = res.data;
  });

  // 获取采集商品分类数据
  product.rawcategory
    .rawcategoryList({
      data: from,
    })
    .then((res) => {
      sys_currency_raw.value = res.data;
    });
  // 来源网站
  product.collectionsite
    .collectionsiteList({
      data: from,
    })
    .then((res) => {
      host_type.value = res.data;
    });
};

// 快速审核勾选id，集成公共接口
const publicFastId = (index, newIdList, e) => {
  let newFrom = {};
  newFrom = {
    ...e,
    ids: newIdList,
  };

  product.draft
    .productdraftAudit({
      data: newFrom,
    })
    .then((res) => {
      if (res.code === 200) {
        auditOpen.value = false;
        getList();
      }
    });
};
const handleMining = (row, command) => {
  proxy.$modal
    .confirm(`是否需要重新${command.title}`)
    .then(() => {
      product.recollection.recollectionAdd({
        data: {
          id: row.id,
          recollectionType: command.recollectionType
        }
      }).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(res.message);
        }
      })
    })
}
const rowSelectable = (row, index) => {
  return row?.rowStatue !== 1;
};
const speedCancel = () => {
  speedVisible.value = false;
};
const handleSpeedSure = () => {
  speedVisible.value = false;
  getList();
};
const changeAuditStatus = (e) => {
  showBtn.value = e === "passed" ? false : true;
  getList();
};
// 批量审核==》来源网站
const choseWebSite = (e) => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      collectionSiteId: e,
    },
  };
  // 获取采集商品分类数据
  product.rawcategory
    .rawcategoryList({
      data: from,
    })
    .then((res) => {
      queryParams.param.rawCategoryId = null
      site_currency_raw.value = res.data;
    });
}
const incidentList = [
  {
    id: 0,
    title: '商品采集',
    recollectionType: 'product'
  }, {
    id: 1,
    title: '分类采集',
    recollectionType: 'category'

  }, {
    id: 2,
    title: '整站采集',
    recollectionType: 'site'

  }
]
const rules = reactive({
  collectionSiteId: [{ required: true, message: "请选择", trigger: "blur" }],
});
const shopProductRules = reactive({
  newIDs: [
    {
      pattern: /^(0|[1-9]\d*)$/,
      message: "请正确输入ID",
      trigger: "blur",
    },
  ],
})

</script>
<style lang="scss" scoped>
.product_tag {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.tabs_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
}

.container {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  justify-content: flex-start;
  /* 左对齐 */
  align-items: flex-start;
  /* 顶部对齐 */
  gap: 10px;
  /* 控制间距 */
  max-width: 150px;
  /* 设定最大宽度，便于测试换行效果 */
}

.my-content {
  background: aqua;
}
</style>